const app = getApp()
const imgBaseUrl = app.globalData.imgBaseUrl;
const imgPreUrl = app.globalData.imgPreUrl;
Page({
  data: {
    imgBaseUrl: imgBaseUrl,
    imgPreUrl: imgPreUrl,
    zhekouPrice:0,
    shopPrice:0,
    selectAll:false,
    tuijianList: []
  },
  onShow: function () {
    var that = this;
    app.func.postReq('/text/index.php/home/user/userinfo', {}, function (res) {
      that.setData({
        vip: res.user.grade
      })
    })
    app.func.postReq('/text/index.php/home/shopcar/carlists', {}, function (res) {
      var selectAll=false;
      if(res.cars){
        var buzu=0;
        for(let i=0,len=res.cars.length;i<len;i++){
          if (res.cars[i].pnum > 0 && res.cars[i].pstate==1){
            res.cars[i].selected = true;
          }else{
            res.cars[i].selected = false;
            buzu+=1;            
          }
        }
        selectAll = buzu?false:true;
        console.log(selectAll);
      }
      that.setData({
        goodsList: res.cars ? res.cars:[],
        tuijianList: res.tj_pros,
        selectAll:selectAll,
        byprice:res.web.byprice,
        web:res.web,
        grade:res.grade
      })
      that.totalPrice();
    })
    app.func.postReq('/text/index.php/home/shopcar/cars',{},function(res){
      if(res){
        that.setData({
          cartNum:res
        })
        wx.setTabBarBadge({
          index: 2,
          text: res.toString(),
        })
      }else{
        wx.removeTabBarBadge({
          index:2
        })
      }
    })
  },
  onHide: function () {
  
  },
  createOrder:function(){
    var that=this;
    var goodsList=that.data.goodsList;
    var carids=[];
    for(let i=0,len=goodsList.length;i<len;i++){
      if(goodsList[i].selected){
        if (parseFloat(goodsList[i].num) > parseFloat(goodsList[i].pnum)){
          wx.showModal({
            content: `${goodsList[i].pname}仅剩${goodsList[i].pnum}件啦，请修改购买数量~`,
            showCancel: false,
            confirmColor:"#F84F7C"
          })
          return;
        }
        carids.push(goodsList[i].id);
      }
    }
    if(carids.length==0){
      wx.showToast({
        title: '请选择商品',
        icon:'none'
      })
      return;
    }
    var zongjia=that.data.vip==0?that.data.shopPrice:that.data.zhekouPrice;
    wx.navigateTo({
      url: `../order/order?carids=${carids}&totalPrice=${that.data.totalPrice}&yunfei=${that.data.yunfei}&zongjia=${zongjia}&vip=${that.data.vip}`
    })
  },
  addCart: function (e) {
    const that = this;
    var { id, index,pnum,num,price,gtype } = e.currentTarget.dataset;
    gtype = gtype ? gtype : '';
    if(parseFloat(num)>=parseFloat(pnum)){
      wx.showToast({
        title: '库存不足！',
        icon:'none'
      })
      return;
    }
    var goodsList = that.data.goodsList;   
    var cartNum=that.data.cartNum;
    cartNum+=1;
    wx.setTabBarBadge({
      index: 2,
      text: cartNum.toString(),
    })
    that.setData({
      cartNum:cartNum
    })

    app.func.postReq('/text/index.php/home/shopcar/addscar', { pid: id, num: 1,goods_price:price,goods_type:gtype }, function (res) {

      if (parseFloat(res) == -1) {
        wx.showToast({
          title: '添加失败！',
          icon: 'none'
        });
        return false;
      }
      goodsList[index].num = res;
      that.setData({
        goodsList: goodsList,
      })
      that.totalPrice();
      that.isSelectAll();

    })
  },
  jianCart: function (e) {
    const that = this;
    var { id, index, gtype } = e.currentTarget.dataset;
    gtype = gtype ? gtype : '';
    var goodsList = that.data.goodsList;
    var cartNum=that.data.cartNum;
    if (goodsList[index].num == 1) {
      wx.showModal({
        content: '您确定删除该商品吗？',
        confirmColor:'#f84880',
        success: function (res) {
          if (res.confirm) {
                
            app.func.postReq('/text/index.php/home/shopcar/minuescar', { pid: id, num: 1 ,goods_type:gtype}, function (res) {

              if(res <= 0){

                  goodsList.splice(index,1);
                  cartNum -= 1;
                if (cartNum > 0) {
                  wx.setTabBarBadge({
                    index: 2,
                    text: cartNum.toString(),
                  })
                } else {
                  wx.removeTabBarBadge({
                    index: 2
                  })
                }
                that.setData({
                  goodsList: goodsList,
                  cartNum:cartNum
                });

                that.totalPrice();
                that.isSelectAll();
              }
              
            })
            
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      return;
    }
    cartNum-=1;
    if (cartNum > 0) {
      wx.setTabBarBadge({
        index: 2,
        text: cartNum.toString(),
      })
    } else {
      wx.removeTabBarBadge({
        index: 2
      })
    }
    that.setData({
      cartNum:cartNum
    })
    app.func.postReq('/text/index.php/home/shopcar/minuescar', { pid: id, num: 1, goods_type:gtype }, function (res) {

        if(res != -1){

          goodsList[index].num = parseFloat(res);
          that.setData({
            goodsList: goodsList,
          })
          that.totalPrice();
          that.isSelectAll();
        }
        
    })
  },
  selectGoods:function(e){
    var index=e.currentTarget.dataset.index;
    var goodsList=this.data.goodsList;
    goodsList[index].selected = !goodsList[index].selected;
    this.setData({
      goodsList: goodsList
    })
    this.totalPrice();
    this.isSelectAll();
  },
  sellectAll:function(){
    var selectAll = this.data.selectAll;
    var goodsList = this.data.goodsList;
    var selected = selectAll?false:true;
    for (let i = 0, len = goodsList.length; i < len; i++) {
      console.log(goodsList[i].pnum);
      console.log(goodsList[i].pnum>0);
      goodsList[i].selected = goodsList[i].pnum>0?selected:false;
    }
    this.totalPrice();
    this.setData({
      goodsList: goodsList,
      selectAll: !selectAll
    })
    if (selectAll) {//取消全选合计为0
      this.setData({
        totalPrice: 0,
        yunfei: 0
      })
    }
  },
  isSelectAll: function (){
    var goodsList = this.data.goodsList;
    var selNum=0;
    for (let i = 0, len = goodsList.length;i<len;i++){
      if (goodsList[i].selected){
        selNum+=1;
      }
    }
    this.setData({
      selectAll: selNum == goodsList.length?true:false
    })
    if (selNum == 0) {//取消全选合计为0
      this.setData({
        totalPrice: 0,
        yunfei:0
      })
    }
  },
  delCart(e){
    var that=this;
    var {id,index,num}=e.currentTarget.dataset;
    var goodsList = this.data.goodsList;
    var cartNum=this.data.cartNum;
    wx.showModal({
      content: '您确认删除此商品吗？',
      confirmColor:'#f84880',
      success:function(res){
        if(res.confirm){
          app.func.postReq('/text/index.php/Home/shopcar/delcars',{carids:id},function(res){
            if(parseFloat(res)==1){
              goodsList.splice(index,1);
              that.setData({
                goodsList: goodsList
              })
              cartNum-=num;
              if (cartNum > 0) {
                wx.setTabBarBadge({
                  index: 2,
                  text: cartNum.toString(),
                })
              } else {
                wx.removeTabBarBadge({
                  index: 2
                })
              }
              that.selectAll();
            }
          })
        }
      }
    })
  },
  totalPrice:function(res){

    console.group('totalPrice');
    var that=this;
    var goodsList = this.data.goodsList;
    var byprice=this.data.web.byprice;
    if (!goodsList){
      return;
    }
    var shopPrice=0;
    var zhekouPrice=0;
    var selnum=0;
    console.log(zhekouPrice);
    for(let i=0,len=goodsList.length;i<len;i++){
      if(goodsList[i].selected){
        selnum+=1;
        shopPrice += parseFloat(goodsList[i].price) * parseFloat(goodsList[i].num);
        console.log(parseFloat(goodsList[i].goods_price) , parseFloat(goodsList[i].num));
        goodsList[i].goods_price = goodsList[i].goods_price ? goodsList[i].goods_price : 0;
        zhekouPrice += parseFloat(goodsList[i].goods_price) * parseFloat(goodsList[i].num);
        /*if (parseFloat(goodsList[i].user_price)){
          zhekouPrice += parseFloat(goodsList[i].user_price) * parseFloat(goodsList[i].num);
        }else{
          zhekouPrice +=parseFloat(goodsList[i].price) * parseFloat(goodsList[i].num)
        }*/
      }
    }
    console.log(zhekouPrice);
    var totalPrice = zhekouPrice;
    // var totalPrice = this.data.vip == 0 ? shopPrice : zhekouPrice;
    var tkprice=parseFloat(this.data.web.tkprice);
    var yunfei = totalPrice<byprice&&selnum>0?tkprice:0;//运费
    var notyfPrice = byprice - totalPrice;
    totalPrice+=yunfei;

    this.setData({
      shopPrice: Math.round(shopPrice*100)/100,
      zhekouPrice: Math.round(zhekouPrice*100)/100,
      totalPrice: Math.round(totalPrice * 100) / 100,
      yunfei:yunfei,
      notyfPrice: Math.round(notyfPrice * 100) / 100,
      fxprice: parseFloat(this.data.vip) > 0 ? Math.round(zhekouPrice*this.data.grade.discount*100)/100:0
    });

    console.groupEnd();
  }
})